package utils;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import app.cloudstringers.R;
import app.cloudstringers.StatusTab;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

public class Utils {

	private static AlertDialog mAdConnection = null;
	private Context context;
	private static Handler mHandler = new Handler();
	private ProgressDialog mPdWaiting = null;

	public Utils(Context context) {
		setContext(context);
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	/**
	 * Check fill blank
	 */
	public static boolean checkFillBlank(EditText et) {
		if (et.getText().toString().equals("")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Check fill password characters At least 8 characters
	 */
	public static boolean checkFillPassword(EditText et) {
		if (et.getText().toString().length() >= 8) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Check the device to make sure it has the Google Play Services APK. If
	 * it doesn't, display a dialog that allows users to download the APK from
	 * the Google Play Store or enable it in the device's system settings.
	 */
	public static boolean checkPlayServices(Context context) {
		int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, (Activity) context,
						9000).show();
			} else {
				Log.e("", "This device is not supported.");
				((Activity) context).finish();
			}
			return false;
		}
		return true;
	}

	/**
	 * Delete cache
	 */
	// public static void trimCache(Context context) {
	// try {
	// File dir = context.getCacheDir();
	// if (dir != null && dir.isDirectory()) {
	// deleteDir(dir);
	// }
	// } catch (Exception e) {
	// // TODO: handle exception
	// }
	// }

	public static boolean deleteDir(Context context) {
		File dir = context.getCacheDir();
		// if (dir != null && dir.isDirectory()) {
		// String[] children = dir.list();
		// for (int i = 0; i < children.length; i++) {
		// boolean success = deleteDir(new File(dir, children[i]));
		// if (!success) {
		// return false;
		// }
		// }
		// }

		// The directory is now empty so delete it
		return dir.delete();
	}

	public static boolean checkIntegerValue(EditText et) {
		try {
			Integer.parseInt(et.getText().toString());

			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * Disable tab widget in status tab
	 */
	public static void disableTabWidgetInStatusTab(int index) {
		for (int i = 0; i < index; i++) {
			StatusTab.tabHost.getTabWidget().getChildTabViewAt(i)
			.setEnabled(false);
		}
	}

	/**
	 * Get current day
	 * 
	 * @return
	 */
	public static String getCurrentDate() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, 0);

		/**
		 * Add Date of 12 AM
		 */
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);

		Date mDateBegin = cal.getTime();

		/**
		 * Add Date of 11 PM
		 */
		cal.add(Calendar.DAY_OF_MONTH, 1);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);

		Date mDateEnd = cal.getTime();

		SimpleDateFormat sdf = new SimpleDateFormat("dd MMM");

		return sdf.format(mDateBegin);
	}

	/**
	 * Get current month
	 * 
	 * @return
	 */
	public static String getCurrentMonth() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, 0);
		SimpleDateFormat sdf = new SimpleDateFormat("MMM yyyy");
		return sdf.format(cal.getTime());
	}

	public static String getCurrentWeek(Calendar mCalendar) {
		Date date = new Date();
		mCalendar.setTime(date);

		// 1 = Sunday, 2 = Monday, etc.
		int day_of_week = mCalendar.get(Calendar.DAY_OF_WEEK);

		int monday_offset;
		if (day_of_week == 1) {
			monday_offset = -6;
		} else
			monday_offset = (2 - day_of_week); // need to minus back
		mCalendar.add(Calendar.DAY_OF_YEAR, monday_offset);

		Date mDateMonday = mCalendar.getTime();

		// Save Monday Date into singleton

		// return 6 the next days of current day (object cal save current day)
		mCalendar.add(Calendar.DAY_OF_YEAR, 6);
		Date mDateSunday = mCalendar.getTime();

		// Save Sunday date into singleton

		// Get format date
		String strDateFormat = "dd MMM";
		SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

		String MONDAY = sdf.format(mDateMonday);
		String SUNDAY = sdf.format(mDateSunday);

		// Sub String
		if ((MONDAY.substring(3, 6)).equals(SUNDAY.substring(3, 6))) {
			MONDAY = MONDAY.substring(0, 2);
		}

		return MONDAY + " - " + SUNDAY;
	}

	/**
	 * Get current year
	 * 
	 * @return
	 */
	public static String getCurrentYear() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.YEAR, 0);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		return sdf.format(cal.getTime());
	}

	/**
	 * Get Float format with 4 digits
	 */
	public static String getFloatFormat(float value) {
		return String.format("%.3f", value);
	}

	/**
	 * Get yesterday
	 * 
	 * @return
	 */
	public static String getLastDate(int i) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_YEAR, -i);

		/**
		 * Add Date of 12 AM
		 */
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);

		Date mDateBegin = cal.getTime();

		/**
		 * Add Date of 11 PM
		 */
		cal.add(Calendar.DAY_OF_MONTH, 1);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);

		Date mDateEnd = cal.getTime();

		SimpleDateFormat sdf = new SimpleDateFormat("dd MMM");

		return sdf.format(mDateBegin);
	}

	/**
	 * Get previous month
	 * 
	 * @return
	 */
	public static String getLast1Month(int i) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -i);
		SimpleDateFormat sdf = new SimpleDateFormat("MMM yyyy");
		return sdf.format(cal.getTime());
	}

	/**
	 * Get previous 3 months ago
	 * 
	 * @return
	 */
	public static String getLast3Months(int i) {
		Calendar cal = Calendar.getInstance();

		if (i == 0) {
			cal.add(Calendar.MONTH, -3 * i);
		} else {
			cal.add(Calendar.MONTH, -3 * i + 1);
		}

		SimpleDateFormat sdf = new SimpleDateFormat("MMM yyyy");
		return sdf.format(cal.getTime());
	}

	public static String getLast3MonthsFirstIndex(int i) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -3 * i);

		SimpleDateFormat sdf = new SimpleDateFormat("MMM yyyy");
		return sdf.format(cal.getTime());
	}

	public static String getLastWeek(Calendar mCalendar) {
		// Monday
		mCalendar.add(Calendar.DAY_OF_YEAR, -13);
		Date mDateMonday = mCalendar.getTime();

		// Save into singleton

		// Sunday
		mCalendar.add(Calendar.DAY_OF_YEAR, 6);
		Date mDateSunday = mCalendar.getTime();

		// Save into singleton

		// Date format
		String strDateFormat = "dd MMM";
		SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

		String MONDAY = sdf.format(mDateMonday);
		String SUNDAY = sdf.format(mDateSunday);

		// Substring
		if ((MONDAY.substring(3, 6)).equals(SUNDAY.substring(3, 6))) {
			MONDAY = MONDAY.substring(0, 2);
		}

		return MONDAY + " - " + SUNDAY;
	}

	/**
	 * Get previous year ago
	 * 
	 * @return
	 */
	public static String getLastYear(int i) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.YEAR, -i);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		return sdf.format(cal.getTime());
	}

	public static String getNextWeek(Calendar mCalendar) {
		// Monday
		mCalendar.add(Calendar.DAY_OF_YEAR, 1);
		Date mDateMonday = mCalendar.getTime();

		// Save into singleton

		// Sunday
		mCalendar.add(Calendar.DAY_OF_YEAR, 6);
		Date Week_Sunday_Date = mCalendar.getTime();

		// Save into singleton

		// Date format
		String strDateFormat = "dd MMM";
		SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

		String MONDAY = sdf.format(mDateMonday);
		String SUNDAY = sdf.format(Week_Sunday_Date);

		// Sub string
		if ((MONDAY.substring(3, 6)).equals(SUNDAY.substring(3, 6))) {
			MONDAY = MONDAY.substring(0, 2);
		}

		return MONDAY + " - " + SUNDAY;
	}

	/**
	 * Enable tab widget in status tab
	 */
	public static void enableTabWidgetInStatusTab(int index) {
		for (int i = 0; i < index; i++) {
			StatusTab.tabHost.getTabWidget().getChildTabViewAt(i)
			.setEnabled(true);
		}
	}

	/**
	 * Get real path from Uri
	 * 
	 * @param context
	 * @param contentUri
	 * @return
	 */
	public String getRealPathFromURI(Context context, Uri contentUri) {
		Cursor cursor = null;
		try {
			String[] proj = { MediaColumns.DATA };
			cursor = context.getContentResolver().query(contentUri, proj, null,
					null, null);
			int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
	}

	/**
	 * Return date in specified format.
	 * 
	 * @param milliSeconds
	 *            Date in milliseconds
	 * @param dateFormat
	 *            Date format
	 * @return String representing date in specified format
	 */
	public static String getDate(long milliSeconds, String dateFormat) {
		// Create a DateFormatter object for displaying date in specified
		// format.
		DateFormat formatter = new SimpleDateFormat(dateFormat);

		// Create a calendar object that will convert the date and time value in
		// milliseconds to date.
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(milliSeconds);
		return formatter.format(calendar.getTime());
	}

	/**
	 * get Number (float or int) from String 
	 */
	public static String getNumberOfString(String str){
		str = str.replaceAll("[^\\d.]", "");
		return str;
	}

	/**
	 * Hide alert connection dialog
	 */
	public static void hideConnectionDialog() {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				mAdConnection.dismiss();
			}
		});
	}

	/**
	 * Hide progress dialog
	 */
	public void hideProgressDialog() {
		if (mPdWaiting != null && mPdWaiting.isShowing()) {
			mPdWaiting.dismiss();
			mPdWaiting = null;
		}
	}

	/**
	 * Hidden keyboard in page
	 */
	/**
	 * Hidden keyboard
	 */
	public void hideSoftKeyboard() {
		try {
			InputMethodManager mImm = (InputMethodManager) context
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			mImm.hideSoftInputFromWindow(((Activity) context).getCurrentFocus()
					.getWindowToken(), 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void hideSoftKeyboard(Activity activity) {
		activity.getWindow().setSoftInputMode(InputMethodManager.RESULT_HIDDEN);
	}

	/**
	 * Hidden keyboard of edit text
	 */
	public void hideSoftKeyboard(EditText et) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
	}

	/**
	 * Initial data for full screen dialog
	 */
	public void initialFullWidthScreenDialog(Dialog dialog) {
		// Initial layout for dialog
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
		lp.copyFrom(dialog.getWindow().getAttributes());
		lp.width = LayoutParams.FILL_PARENT;
		lp.height = LayoutParams.WRAP_CONTENT;

		dialog.getWindow().setAttributes(lp);
	}

	/**
	 * Initial data for full screen dialog
	 */
	public void initialFullScreenDialog(Dialog dialog) {
		// Initial layout for dialog
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
		lp.copyFrom(dialog.getWindow().getAttributes());
		lp.width = LayoutParams.FILL_PARENT;
		lp.height = LayoutParams.FILL_PARENT;

		dialog.getWindow().setAttributes(lp);
	}

	/**
	 * Initialize alert connection dialog
	 */
	public static void initialConnectionDialog(final Context context) {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				mAdConnection = new AlertDialog.Builder(context).create();
				mAdConnection.setTitle(context
						.getString(R.string.title_failed_connection));
				mAdConnection.setIcon(R.drawable.ibtn_error_normal);
				mAdConnection.setCancelable(false);
				mAdConnection.setMessage(context
						.getString(R.string.content_failed_server_connection));
				mAdConnection.setButton(DialogInterface.BUTTON_POSITIVE,
						context.getString(R.string.try_again),
						new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9,
							int whichButton) {
						hideConnectionDialog();

						// New intent to wireless setting
						context.startActivity(new Intent(
								android.provider.Settings.ACTION_WIRELESS_SETTINGS));
					}
				});
				mAdConnection.setButton(DialogInterface.BUTTON_NEGATIVE,
						context.getString(R.string.quit),
						new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9,
							int whichButton) {
						android.os.Process
						.killProcess(android.os.Process.myPid());
					}
				});
			}
		});
	}

	/**
	 * Check network connection
	 */
	public boolean isNetworkOnline() {
		boolean status = false;
		try {
			ConnectivityManager cm = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo netInfo = cm.getNetworkInfo(0);
			if (netInfo != null
					&& netInfo.getState() == NetworkInfo.State.CONNECTED) {
				status = true;
			} else {
				netInfo = cm.getNetworkInfo(1);
				if (netInfo != null
						&& netInfo.getState() == NetworkInfo.State.CONNECTED)
					status = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return status;
	}
	/**
	 * remove String Duplicates
	 */
	public static String removeDuplicatesInString(String str)
	{
		str = str.trim();
	    List<String> mAlResult = new ArrayList<String>();
	    String[] mASplitString = str.split(",");
	    StringBuilder mSbResult = new StringBuilder();
	    for (int i = 0; i < mASplitString.length; ++i)
	    {
	        if (!mAlResult.contains(mASplitString[i]))
	        {
	        	mAlResult.add(mASplitString[i]);
	        	mSbResult.append(',');
	        	mSbResult.append(mASplitString[i]);
	        }
	    }
	    return mSbResult.substring(1);

	}

	/**
	 * Remove view parent
	 */
	public static void removeViewParent(View v) {
		((ViewGroup) v.getParent()).removeView(v);
	}

	/**
	 * Set only default language
	 * 
	 * @param context
	 * @param lang
	 */
	public static void setDefaultLanguage(Context context, String lang) {
		Locale locale = new Locale(lang);
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		context.getResources().updateConfiguration(config,
				context.getResources().getDisplayMetrics());
	}

	/**
	 * Show action sheet dialog
	 * 
	 * @param resource
	 */
	public static PopupWindow showActionSheetDialog(Context context, View v) {
		// Get display of the screen
		Display display = ((Activity) context).getWindowManager()
				.getDefaultDisplay();
		Point p = new Point();
		display.getSize(p);

		// Creating the PopupWindow
		final PopupWindow mPw = new PopupWindow(context);
		mPw.setContentView(v);
		mPw.setWidth(LayoutParams.MATCH_PARENT);
		mPw.setHeight(LayoutParams.WRAP_CONTENT);

		// Displaying the pop up at the specified location.
		mPw.showAtLocation(v, Gravity.BOTTOM, 0, 0);

		return mPw;
	}

	/**
	 * Hide alert connection dialog
	 */
	public static void showConnectionDialog() {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				mAdConnection.show();
			}
		});
	}

	/**
	 * show connection timeout dialog
	 */
	public void showConnectionTimeoutDialog(final Context context,
			final Class<?> object) {
		mAdConnection = new AlertDialog.Builder(context).create();
		mAdConnection.setTitle(context
				.getString(R.string.title_failed_connection));
		mAdConnection.setIcon(R.drawable.ibtn_error_normal);
		mAdConnection.setCancelable(false);
		mAdConnection.setMessage(context
				.getString(R.string.content_failed_server_connection));
		mAdConnection.setButton(DialogInterface.BUTTON_POSITIVE,
				context.getString(R.string.try_again),
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
				((Activity) context).finish();
				context.startActivity(new Intent(context, object));
			}
		});
		mAdConnection.setButton(DialogInterface.BUTTON_NEGATIVE,
				context.getString(R.string.quit),
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9, int whichButton) {
				android.os.Process.killProcess(android.os.Process
						.myPid());
			}
		});
		mAdConnection.show();
	}

	/**
	 * Show Exit dialog
	 */
	public static void showExitDialog(Context context) {
		new AlertDialog.Builder(context)
		.setTitle(R.string.exit)
		.setCancelable(false)
		.setMessage(R.string.content_exit)
		.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9,
					int whichButton) {
				android.os.Process
				.killProcess(android.os.Process.myPid());
			}
		})
		.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog9,
					int whichButton) {
			}
		}).show();
	}

	/**
	 * Show progress dialog
	 */
	public void showProgressDialog() {
		if (mPdWaiting == null) {
			mPdWaiting = ProgressDialog.show(context,
					context.getString(R.string.title_loading),
					context.getString(R.string.content_loading));
		}
	}
}
